package cc.admin.modules.graduate.controller;

import cc.admin.common.api.vo.Result;
import cc.admin.common.aspect.annotation.AutoLog;
import cc.admin.common.sys.base.controller.BaseController;
import cc.admin.common.sys.query.QueryGenerator;
import cc.admin.common.util.RedisUtil;
import cc.admin.modules.graduate.entity.Forum;
import cc.admin.modules.graduate.entity.Topic;
import cc.admin.modules.graduate.service.IForumService;
import cc.admin.modules.sys.entity.SysCascade;
import cc.admin.modules.sys.service.ISysCascadeService;
import cc.admin.modules.graduate.entity.UserForumLike;
import cc.admin.modules.graduate.service.IUserForumLikeService;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 用户评论点赞表
 * @Author: cc-admin
 * @Date: 2025-02-26
 * @Version: V1.0.0
 */
@Slf4j
@Api(tags = "用户评论点赞表")
@RestController
@RequestMapping("/user/forumLike")
public class UserForumLikeController extends BaseController<UserForumLike, IUserForumLikeService> {
    @Autowired
    private IUserForumLikeService userForumLikeService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IForumService forumService;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "用户评论点赞表-分页列表查询")
    @ApiOperation(value = "用户评论点赞表-分页列表查询", notes = "用户评论点赞表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList() {
//		QueryWrapper<UserForumLike> queryWrapper = QueryGenerator.initQueryWrapper(new UserForumLike(), req.getParameterMap());
//		if (StrUtil.isNotEmpty(key)) {
//
//		}
//
//		Page<UserForumLike> page = new Page<UserForumLike>(pageNo, pageSize);
//		IPage<UserForumLike> pageList = userForumLikeService.page(page, queryWrapper);

        ArrayList<Forum> countUserIdByForumId = (ArrayList<Forum>) redisUtil.get("countUserIdByForumId");
        if (countUserIdByForumId!=null){
            return Result.ok(countUserIdByForumId);
        }
        JSONObject jsonObject = userForumLikeService.countUserIdByForumId();
        JSONObject group_by_forum_id = jsonObject.getJSONObject("group_by_forum_id");
        JSONArray bucketsArr = group_by_forum_id.getJSONArray("buckets");
        ArrayList<Forum> forums = new ArrayList<>();
        bucketsArr.forEach(bucket -> {
            Map<String, Object> stringObjectMap = parseStringToMap(String.valueOf(bucket));
            Forum forum = forumService.getById((String) stringObjectMap.get("key"));
            String likeNum = stringObjectMap.get("doc_count").toString();
            forum.setLikeNum(likeNum);
            if (forum.getViedoUrlText() != null && !forum.getViedoUrlText().equals("")) {
                forum.setViedoUrls(Arrays.stream(forum.getViedoUrlText().split(",")).collect(Collectors.toList()));
            }
            LambdaQueryWrapper<Forum> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Forum::getParentId, forum.getId());
            lambdaQueryWrapper.isNull(Forum::getDiscussion);
            List<Forum> childlist = forumService.list(lambdaQueryWrapper);
            childlist.forEach(childForum -> {
                forumContent(childForum);
                LambdaQueryWrapper<Forum> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(Forum::getParentId, childForum.getId());
                lambdaQueryWrapper2.isNotNull(Forum::getDiscussion);
                List<Forum> childlist2 = forumService.list(lambdaQueryWrapper2);
                childlist2.forEach(childForum2->{
                    forumContent(childForum2);
                    LambdaQueryWrapper<Forum> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper3.eq(Forum::getParentId, childForum2.getId());
                    lambdaQueryWrapper3.isNotNull(Forum::getDiscussion);
                    List<Forum> childlist3 = forumService.list(lambdaQueryWrapper3);
                    childForum2.setChildForums(childlist3);
                });
                childForum.setChildForums(childlist2);
            });
            forum.setChildForums(childlist);
            forums.add(forum);
        });
        redisUtil.set("countUserIdByForumId",forums);
        return Result.ok(forums);
    }

    public void forumContent(Forum forum) {
        String topicLabel = forum.getTopicLabel();
        String topicValue = forum.getTopicValue();
        Topic topic = new Topic(topicLabel, topicValue);
        forum.setTopic(topic);
        if (forum.getViedoUrlText() != null && forum.getViedoUrlText().split(",") != null) {
            List<String> videoUrls = Arrays.stream(forum.getViedoUrlText().split(",")).collect(Collectors.toList());
            forum.setViedoUrls(videoUrls);
        }
    }
    public static Map<String, Object> parseStringToMap(String input) {
        Map<String, Object> map = new HashMap<>();
        if (input != null && input.startsWith("{") && input.endsWith("}")) {
            input = input.substring(1, input.length() - 1);
            String[] parts = input.split(", ");
            for (String part : parts) {
                String[] keyValue = part.split("=");
                if (keyValue.length == 2) {
                    String key = keyValue[0].trim();
                    String value = keyValue[1].trim();
                    if (value.startsWith("{") && value.endsWith("}")) {
                        // 处理子对象
                        Map<String, Object> subMap = parseStringToMap(value);
                        map.put(key, subMap);
                    } else {
                        try {
                            // 尝试转换为数字
                            int intValue = Integer.parseInt(value);
                            map.put(key, intValue);
                        } catch (NumberFormatException e) {
                            // 不是数字则作为字符串处理
                            map.put(key, value);
                        }
                    }
                }
            }
        }
        return map;
    }

    /**
     * 添加
     *
     * @param userForumLike
     * @return
     */
    @AutoLog(value = "用户评论点赞表-添加")
    @ApiOperation(value = "用户评论点赞表-添加", notes = "用户评论点赞表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody UserForumLike userForumLike) {
        userForumLike.setId(IdUtil.objectId());
        userForumLikeService.saveLike(userForumLike);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param userForumLike
     * @return
     */
    @AutoLog(value = "用户评论点赞表-编辑")
    @ApiOperation(value = "用户评论点赞表-编辑", notes = "用户评论点赞表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody UserForumLike userForumLike) {
        userForumLikeService.updateById(userForumLike);
        return Result.ok("编辑成功!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户评论点赞表-通过id删除")
    @ApiOperation(value = "用户评论点赞表-通过id删除", notes = "用户评论点赞表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        userForumLikeService.removeById(id);
        return Result.ok("删除成功!");
    }


}
